package com.example.learnvitamio

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import io.vov.vitamio.LibsChecker
import io.vov.vitamio.MediaPlayer
import java.io.IOException
import java.lang.Exception
import java.lang.IllegalArgumentException

/**
 *
 * @Author： LJH
 * @Time： 2022/7/11
 * @description：
 */
class MediaPlayerDemoAudio:Activity() {
    private var mediaPlay:MediaPlayer? = null
    private var path = ""
    private lateinit var tx:TextView

    companion object{
        const val MEDIA = "media"
        const val LOCAL_AUDIO = 1
        const val STREAM_AUDIO = 2
        const val RESOURCES_AUDIO = 3
        const val LOCAL_VIDEO = 4
        const val STREAM_VIDEO = 5
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!LibsChecker.checkVitamioLibs(this))
            return;
        tx = TextView(this)
        setContentView(tx)
        val bundle = intent.extras
        playAudio(bundle!!.getInt(MEDIA))
    }

    fun playAudio(media:Int){
        try {
            when(media){
                LOCAL_AUDIO -> {
                    path = "http://82.157.163.217/Monsters.mp3"
                    if (path == ""){
                        Toast.makeText(this,"Your audio file must be stored on sdcard.",Toast.LENGTH_SHORT).show()
                    }
                    mediaPlay = MediaPlayer(this)
                    mediaPlay!!.setDataSource(path)
                    mediaPlay!!.prepare()
                    mediaPlay!!.start()
                }
                RESOURCES_AUDIO -> {
                    mediaPlay = createMediaPlayer(this,R.raw.monsters)
                    mediaPlay?.start()
                }
            }
            tx.text = "Playing audio..."
        }catch (e:Exception){
            Log.d("MediaPlayerDemoAudio","error:${e.message}",e)
        }

    }

    private fun createMediaPlayer(context: Context, resid:Int):MediaPlayer?{
        try {
            val afd = context.resources.openRawResourceFd(resid)
            val mp = MediaPlayer(context)
            mp.setDataSource(afd.fileDescriptor)
            afd.close()
            mp.prepare()
            return mp
        }catch (e:IOException){
            Log.d("MediaPlayerDemoAudio","create failed",e)
        }catch (e:IllegalArgumentException){
            Log.d("MediaPlayerDemoAudio","create failed",e)
        }catch (e:SecurityException){
            Log.d("MediaPlayerDemoAudio","create failed",e)
        }
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mediaPlay != null){
            mediaPlay?.release()
            mediaPlay = null
        }
    }
}